package com.im.service.jim;

import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.server.JimServerAPI;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author liuzhiqiang
 */
public class ChatSessionUtil {
    public static void sendNewSessionToUser(String userId) {
        ImPacket packet = getImPacket(userId);
        JimServerAPI.sendToUser(userId, packet);
    }

    public static void sendNewSessionToImChannelContext(ImChannelContext imChannelContext, String userId) {
        ImPacket packet = getImPacket(userId);
        JimServerAPI.send(imChannelContext, packet);
    }

    private static ImPacket getImPacket(String userId) {
        List<ImChannelContext> list = JimServerAPI.getByUserId(userId);
        Set<Object> chatIds = new HashSet<>();
        for (ImChannelContext channelContext : list) {
            if (channelContext.get("chatId") != null) {
                chatIds.add(channelContext.get("chatId"));
            }
        }
        ImPacket packet = new ImPacket();
        packet.setStatus(ImStatus.C10000);
        packet.setCommand(Command.SESSION_CHANGE);
        packet.setBody(new RespBody(Command.SESSION_CHANGE, chatIds).toByte());
        return packet;
    }
}
